package com.xhs.controller;

import com.xhs.dto.request.CommentRequest;
import com.xhs.dto.response.ApiResponse;
import com.xhs.dto.response.CommentResponse;
import com.xhs.entity.Comment;
import com.xhs.entity.Content;
import com.xhs.entity.User;
import com.xhs.security.UserPrincipal;
import com.xhs.service.CommentService;
import com.xhs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 评论管理控制器
 */
@RestController
@RequestMapping("/contents/{contentId}/comments")
@Slf4j
public class CommentController {
    
    @Autowired
    private CommentService commentService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 添加评论
     */
    @PostMapping
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<CommentResponse>> addComment(
            @PathVariable Long contentId,
            @Valid @RequestBody CommentRequest request,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            Comment comment = commentService.addComment(contentId, request, user);
            log.info("用户 {} 评论内容 {} 成功", user.getUsername(), contentId);
            
            return ResponseEntity.ok(ApiResponse.success("评论成功", CommentResponse.fromEntity(comment)));
            
        } catch (Exception e) {
            log.error("添加评论失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("评论失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取评论列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<CommentResponse>>> getComments(
            @PathVariable Long contentId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<Comment> comments = commentService.getContentComments(contentId, page, size);
            Page<CommentResponse> commentResponses = comments.map(CommentResponse::fromEntity);
            return ResponseEntity.ok(ApiResponse.success(commentResponses));
            
        } catch (Exception e) {
            log.error("获取评论列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取评论失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取评论数量
     */
    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> getCommentCount(@PathVariable Long contentId) {
        try {
            long count = commentService.getCommentCount(contentId);
            return ResponseEntity.ok(ApiResponse.success(count));
            
        } catch (Exception e) {
            log.error("获取评论数失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取评论数失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<String>> deleteComment(
            @PathVariable Long contentId,
            @PathVariable Long commentId,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            commentService.deleteComment(commentId, user);
            log.info("用户 {} 删除评论 {} 成功", user.getUsername(), commentId);
            
            return ResponseEntity.ok(ApiResponse.success("删除成功"));
            
        } catch (Exception e) {
            log.error("删除评论失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("删除失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取评论的回复列表
     */
    @GetMapping("/{commentId}/replies")
    public ResponseEntity<ApiResponse<Page<CommentResponse>>> getCommentReplies(
            @PathVariable Long contentId,
            @PathVariable Long commentId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size) {
        try {
            Page<Comment> replies = commentService.getCommentReplies(commentId, page, size);
            Page<CommentResponse> replyResponses = replies.map(CommentResponse::fromEntity);
            return ResponseEntity.ok(ApiResponse.success(replyResponses));
            
        } catch (Exception e) {
            log.error("获取回复列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取回复失败: " + e.getMessage()));
        }
    }
} 